<template>
  <div>
    <h1>{{id ? '编辑' : '新建'}}分类</h1>
    <el-form label-width="120px" :model="category" @submit.native.prevent="save">
      <el-form-item label="分类名称">
        <el-input v-model="category.name" :clearable="true"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      category: {}
    };
  },
  methods: {
    async fetch() {
      const res = await this.$http.get(`rest/categories/${this.id}`);
      this.category = res.data;
    },
    async save() {
      if (this.id) {
        await this.$http.put(`rest/categories/${this.id}`, this.category);
      } else {
        await this.$http.post("rest/categories", this.category);
      }
      this.$router.push("/category/list");
      this.$message({
        message: "保存成功",
        type: "success"
      });
    }
  },
  created() {
    this.id && this.fetch();
  },
};
</script>
<style scoped>
</style>